<?php
namespace app\common\controller;
use app\common\model\Admin;
use app\common\model\AuthRule;
use app\common\model\AuthGroupAccess;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use think\facade\Cookie;
use think\Model;

class AdminBase extends Base
{
    protected $noLogin = []; // 不用权限认证和登录的方法
    protected $noAuth = []; // 不用权限认证要登录的方法

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        !$this->checkLogin() && $this->redirect(url('/admin/index/login'));
        !$this->checkAuth() && $this->error('没有权限，请联系管理员');
        if ($this->request->isGet()) {
            //View::assign('navbar', list_to_tree($this->getNavbar()));
            //View::assign('breadcrumb', array_reverse(explode(',', $this->getBreadcrumb())));
            View::assign('empty', '<tr><td colspan="20">~~暂无数据</td></tr>');
        }
    }

    // 检查登录
    public function checkLogin()
    {
        if (!is_admin_login() &&
            !in_array($this->request->action(), $this->noLogin)) {
            return false;
        }
        return true;
    }

    // 权限认证
    public function checkAuth()
    {
        if (Session::get('admin_auth.admin_id') != '1' &&
            !in_array($this->request->action(), $this->noLogin) &&
            !in_array($this->request->action(), $this->noAuth) &&
            !(new \core\Auth())->check('admin/'
                . to_under_score($this->request->controller()) . '/'
                . $this->request->action(), Session::get('admin_auth.admin_id'))) {
            return false;
        }
        return true;
    }

    // 获取导航栏
    public function getNavbar()
    {
        $where = ['type' => 'nav', 'status' => 1];
        if (Session::get('admin_auth.admin_id') != '1') {
            $access  = AuthGroupAccess::with('authGroup')->where('uid', Session::get('admin_auth.admin_id'))->find();
            //$where['id'] = ['in', $access['rules']];
            if($access){
                $where = "type='nav' and status = '1' and id in(".$access['rules'].")";
            }
        }
        $navs = AuthRule::where($where)->order('sort_order asc')->select();
        return collection($navs)->toArray();
    }

    // 获取面包屑
    public function getBreadcrumb($id = null)
    {
        if ($authRule = AuthRule::where(empty($id) ? ['url' => 'admin/'
            . to_under_score($this->request->controller()) . '/'
            . $this->request->action()] : ['id' => $id])->order('pid desc')->find()) {
            $breadcrumb = $authRule['name'];
            if ($authRule['pid'] != 0) {
                $breadcrumb .= ',' . $this->getBreadcrumb($authRule['pid']);
            }
            return $breadcrumb;
        }
    }
}
